package com.breezelin.freshmarket.adpaters;

/**
 * Created by Breeze Lin
 * 2016/10/20 16:49
 * 1linyufeng1@gmail.com
 */

import android.annotation.SuppressLint;
import android.content.Context;
import android.support.v4.view.PagerAdapter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.breezelin.freshmarket.R;
import com.breezelin.freshmarket.entities.data.HomeContent;
import com.squareup.picasso.Picasso;

import java.util.LinkedList;
import java.util.List;

/**
 * 主页广告位内容
 */
class HomeBannerAdapter extends PagerAdapter {

	/**
	 * 上下文
	 */
	private Context context;
	/**
	 * 广告内容
	 */
	private List<HomeContent> contents;
	/**
	 * 备用的视图控件
	 */
	private List<View> views;
	/**
	 * 广告位监听
	 */
	private BannerListener listener;

	/**
	 * 主页广告位内容适配器
	 *
	 * @param context  上下文
	 * @param contents 内容
	 */
	HomeBannerAdapter(Context context, List<HomeContent> contents, BannerListener listener) {
		this.context = context;
		this.contents = contents;
		views = new LinkedList<>();
		this.listener = listener;
	}

	@Override
	public int getCount() {
		int size = 0;
		if (contents != null) {
			size = contents.size();
		}
		return size;
	}

	@Override
	public boolean isViewFromObject(View view, Object object) {
		return view == object;
	}

	@SuppressLint("InflateParams")
	@Override
	public Object instantiateItem(ViewGroup container, int position) {

		// 先从回收过的视图控件中找，没有的话才重建一个
		View itemView;
		if (views.size() == 0) {
			// 与列表中其他项目公用布局
			itemView = LayoutInflater.from(context).inflate(R.layout.item_home_content, null);
			// 为itemView设置监听
			itemView.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					listener.onBannerClick((HomeContent) v.getTag());
				}
			});
		} else {
			// 使用已经创建好的视图控件
			itemView = views.get(0);
			// 一旦被重复利用，即从集合移除
			views.remove(itemView);
		}
		ImageView imgView = (ImageView) itemView.findViewById(R.id.img);
		TextView txtView = (TextView) itemView.findViewById(R.id.txt);

		// 根据内容设置视图
		HomeContent content = contents.get(position);
		Picasso.with(context).load(content.getPictureUrl()).into(imgView);
		txtView.setText(content.getBannerName());
		container.addView(itemView);
		// 将内容绑定给视图
		itemView.setTag(content);
		return itemView;
	}

	@Override
	public void destroyItem(ViewGroup container, int position, Object object) {
		View view = (View) object;
		container.removeView(view);
		views.add(view);
	}

	/**
	 * 广告区监听
	 */
	interface BannerListener {
		void onBannerClick(HomeContent content);
	}
}
